package cn.itcast.client;

import cn.itcast.message.RpcRequestMessage;
import cn.itcast.protocol.MessageCodecSharable;
import cn.itcast.protocol.ProcotolFrameDecoder;
import cn.itcast.server.handler.RpcMessageResponseHandler;
import cn.itcast.server.service.HelloService;
import cn.itcast.util.IdUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultPromise;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Proxy;

@Slf4j
public class RpcClientManager {

    private static Channel channel;

    private static final Object LOCK = new Object();

    public static void main(String[] args) {
        HelloService proxyService = getProxyService(HelloService.class);
        System.out.println(proxyService.sayHello("jack"));
        System.out.println(proxyService.sayHello("tony"));
        System.out.println(proxyService.sayHello("tom"));
    }

    public static <T> T getProxyService(Class<T> serviceClass) {
        ClassLoader classLoader = serviceClass.getClassLoader();
        Class[] classes = new Class[]{serviceClass};
        Integer seqId = IdUtil.genId();
        Object proxyInstance = Proxy.newProxyInstance(classLoader, classes, (proxy, method, args) -> {
            // 将方法调用转换为对象
            RpcRequestMessage rpcRequestMessage = new RpcRequestMessage(seqId,
                    serviceClass.getName(),
                    method.getName(),
                    method.getReturnType(),
                    method.getParameterTypes(),
                    args);
            // 将消息发出去
            Channel channel = getChannelInstance();
            channel.writeAndFlush(rpcRequestMessage);

            // 准备一个promise对象来接接收结果                   指定promise对象异步接收结果的线程
            DefaultPromise<Object> promise = new DefaultPromise<>(channel.eventLoop());
            RpcMessageResponseHandler.PROMISES.put(seqId,promise);
            // 等待结果
           promise.await();
           if (promise.isSuccess()){
               return promise.getNow();
           }else {
               throw new RuntimeException(promise.cause());
           }
        });

        return (T) proxyInstance;
    }

    public static Channel getChannelInstance() {
        if (channel != null) {
            return channel;
        }
        synchronized (LOCK) {
            if (channel != null) {
                return channel;
            }
            initChannel();
            return channel;
        }
    }

    private static void initChannel() {
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        RpcMessageResponseHandler RPC_RESP_HANDLER = new RpcMessageResponseHandler();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(group);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProcotolFrameDecoder());
                    ch.pipeline().addLast(LOGGING_HANDLER);
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    ch.pipeline().addLast(RPC_RESP_HANDLER);
                }
            });
            channel = bootstrap.connect("localhost", 8080).sync().channel();
            channel.closeFuture().addListener(future -> {
                group.shutdownGracefully();
            });
        } catch (Exception e) {
            log.error("client error", e);
        }
    }
}
